package us.versus.them.glassifried;

import flash.geom.Rectangle;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.Sprite;

class SliderEvent extends Event {
	public var percentage:Float;
	public function new( p:Float ) {
		super( Event.CHANGE );
		this.percentage = p;
	}
}

class Slider extends Sprite {
	private var slider:Sprite;

	public function new( x,y, w,h, r,g,b ) {
		super();
		this.init( x,y, w,h, r,g,b );
	}

	public function init( x,y, w:Int,h:Int, r:Int,g:Int,b:Int ) {
		this.x = x;
		this.y = y;

		var bg:Sprite;

		// FIXME: assume w > h for now
		if ( w > h ) { 
			var h4 = Math.floor( h / 4 );
			bg = Glassing.glass_it_up( 32, 32, 32, w, h4 );
			bg.y = h / 2 - h4 / 2;

			var h2 = Math.floor( h * 0.7 );
			slider = Glassing.glass_it_up( r, g, b, h2, h2 );
			slider.y = h /2 - h2 / 2;
		} else {

			var w4 = Math.floor( w / 4 );

			//bg = Glassing.glass_it_up( 32, 32, 32, w4, h );
			bg = new Sprite();
			// FIXME: need vertical glass effect...
			bg.graphics.beginFill( 0 );
			bg.graphics.drawRoundRect( 0, 0, w4, h, w4, w4 );
			bg.graphics.endFill();
			bg.x = w / 2 - w4 / 2;

			var w2 = Math.floor( w * 0.7 );
			slider = Glassing.glass_it_up( r, g, b, w2, w2 );
			slider.x = w /2 - w2 / 2;
		}

		var thiz = this;
		slider.addEventListener( MouseEvent.MOUSE_DOWN, function (e) { thiz.slider_click( e ); } );
		bg.addEventListener( MouseEvent.MOUSE_DOWN, function (e) { thiz.bg_click( e ); } );

		addChild( bg );
		addChild( slider );
	}

	public function move( p:Float ) {
		if ( this.width > this.height ) {
			slider.x = p * ( this.width - this.slider.width );
		} else {
			slider.y = p * ( this.height - this.slider.height );
		}
		change( p );
	}

	////

	private function slider_click( e:MouseEvent ) {
		var thiz = this;
		e.target.stage.addEventListener( MouseEvent.MOUSE_MOVE, slider_move );
		// FIXME
		e.target.stage.addEventListener( MouseEvent.MOUSE_UP
			, function (e) { 
				e.target.stage.removeEventListener( MouseEvent.MOUSE_MOVE, thiz.slider_move );
			} 
		);
	}

	// TODO: handle clicking on bar
	private function bg_click( e:MouseEvent ) {
		if ( this.width > this.height ) {
		} else {
		}
	}

	function slider_move( e:MouseEvent ) {
		if ( this.width > this.height ) {
			var o = e.stageX;

			var x = o;
			if ( x < this.x ) x = this.x;
			var max = this.x + this.width - this.slider.width;
			if ( x > max) x = max;

			slider.x = x - this.x;
			change( slider.x / ( this.width - this.slider.width ) );
		} else {
			var o = e.stageY;

			var y = o;
			if ( y < this.y ) y = this.y;
			var max = this.y + this.height - this.slider.height;
			if ( y > max ) y = max;

			slider.y = y - this.y;
			change( slider.y / ( this.height - this.slider.height ) );
		}
	}

	private function change( p:Float ) {
		dispatchEvent( new SliderEvent( p ) );
	}

}
